package com.scrat.huzhenjie.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.scrat.huzhenjie.dao.HuangChengShiDao;
import com.scrat.huzhenjie.model.Account;
import com.scrat.huzhenjie.model.Backup;
import com.scrat.huzhenjie.model.Count;
import com.scrat.huzhenjie.model.Recording;

@Service(value = "huangChengShi")
public class HuangChengShiService {
	@Autowired
	private HuangChengShiDao huangChengShiDao;
	protected static final Logger LOG = Logger.getLogger("huzhenjie");
	public List<Recording> getRecordings(int from,int length,HttpServletRequest request) {
		Account account = getAccount(request);
		if (-1 != from) {
			return huangChengShiDao.getRecordings(from, length,account.getImei());
		} else {
			return huangChengShiDao.getRecordings(account.getImei());
		}
	}
	
	public List<Recording> getRecordings(String[] q,String[] value,boolean fluzzy,int from,int length,HttpServletRequest request) {
		Account account = getAccount(request);
		if (fluzzy) {
			StringBuilder querySQL = new StringBuilder();
			int tmp = 0;
			for (String str : q) {
				querySQL.append(str).append(" LIKE '%").append(value[tmp]).append("%' AND ");
				tmp ++;
			}
			querySQL.append(" _imei = ").append(account.getImei());
			if (-1 != from) {
				return huangChengShiDao.getRecordings(querySQL.toString(), from, length);
			} else {
				return huangChengShiDao.getRecordings(querySQL.toString());
			}
		} else {
			if (-1 != from) {
				return huangChengShiDao.getRecordings(q, value, from, length, account.getImei());
			} else {
				return huangChengShiDao.getRecordings(q, value, account.getImei());
			}
		}
	}
	
	public boolean addRecording(int year,int month,String date,String time,String weather,String mood,String address,String content,String pictureuri,String sounduri,String other,HttpServletRequest request) {
		Account account = getAccount(request);
		boolean result = false;
		try {
			huangChengShiDao.addRecording(year, month, date, time, weather, mood, address, content, pictureuri, sounduri, other,account.getImei());
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public String getRecordingCount(HttpServletRequest request){
		StringBuilder result = new StringBuilder("[");
		Account account = getAccount(request);
		try {
			List<Count> yearCounts = huangChengShiDao.getCountRecording(account.getImei());
			if (!yearCounts.isEmpty()) {
				for (Count count : yearCounts) {
					result.append("{\"year\":")
							.append(count.getResult())
							.append(",\"total\":")
							.append(count.getTotal())
							.append(",\"data\":[");
					List<Count> monthCounts = huangChengShiDao.getCountRecording(account.getImei(), count.getResult());
					if (!monthCounts.isEmpty()) {
						for (Count count2 : monthCounts) {
							result.append("{\"month\":")
									.append(count2.getResult())
									.append(",\"total\":")
									.append(count2.getTotal())
									.append("},");
						}
						result.deleteCharAt(result.lastIndexOf(","));
						}
					result.append("]},");
				}
				result.deleteCharAt(result.lastIndexOf(","));
			}
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
			result = new StringBuilder("[");
		}
		result.append("]");
		return result.toString();
	}
	
	public boolean resetPassword(String oldPassword,String newPassword,HttpServletRequest request) {
		boolean result = false;
		Account account = getAccount(request);
		try {
			Account dbAccount = huangChengShiDao.getAccount(account.getImei());
			oldPassword = md5Encoder(oldPassword);
			if (dbAccount.getPassword().equals(oldPassword)) {
				newPassword = md5Encoder(newPassword);
				huangChengShiDao.updateAccount(dbAccount.getImei(), newPassword, dbAccount.getName(), dbAccount.getSize(), dbAccount.getTime(), dbAccount.getTips(), dbAccount.getOther(), dbAccount.getEmail());
				result = true;
			}
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return result;
	}
	
	/**更新记录
	 * @param id 自增ID
	 * @param year 年份
	 * @param month 月份
	 * @param date 日期
	 * @param time 时间
	 * @param weather 天气
	 * @param mood 心情
	 * @param address 地址
	 * @param content 内容
	 * @param pictureuri 图片地址
	 * @param sounduri 音乐地址
	 * @param other 其它
	 * @return 更新成功返回true
	 */
	public boolean updateRecording(int id,int year,int month,String date,String time,String weather,String mood,String address,String content,String pictureuri,String sounduri,String other,HttpServletRequest request) {
		Account account = getAccount(request);
		boolean result = false;
		try {
			huangChengShiDao.updateRecording(id, year, month, date, time, weather, mood, address, content, pictureuri, sounduri, other,account.getImei());
			result = true;
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return result;
	}
	
	/**删除记录
	 * @param id 自增ID
	 * @return 删除成功返回true
	 */
	public boolean deleteRecording(int id,HttpServletRequest request){
		Account account = getAccount(request);
		boolean result = false;
		try {
			if (-1 != id) {
				huangChengShiDao.delRecording(id,account.getImei());
			} else {
				huangChengShiDao.delRecording(account.getImei());
			}
			result = true;
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return result;
	}
	
	public int getTotalRecording(HttpServletRequest request) {
		Account account = getAccount(request);
		return huangChengShiDao.getTotalRecording(account.getImei());
	}
	
	/**列出所有记录
	 * @return 所有记录列表
	 */
	public List<Backup> getBackups(HttpServletRequest request) {
		Account account = getAccount(request);
		return huangChengShiDao.getbBackups(account.getImei());
	}
	
	public boolean addBackup(String name,String time,String uri,HttpServletRequest request) {
		Account account = getAccount(request);
		boolean result = false;
		try {
			huangChengShiDao.addBackup(name, time, uri,account.getImei());
			result = true;
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return result;
	}
	
	public String uploadFile(HttpServletRequest request,MultipartFile file){
		String result = "";
		if (file != null && file.isEmpty() == false) {
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
			Date date = new Date();
			StringBuilder path = new StringBuilder(request.getSession().getServletContext().getRealPath("/"))
									.append("/resources/")
									.append("test"/*date.getTime()*/)
									.append(".")
									.append(fileType);
			try {
				createPath(path.toString());
				if (uploadFile(file,path.toString())) {
					result = new StringBuilder("http://0.huzhenjie.duapp.com/resources/").append(date.getTime()).append(".").append(fileType).toString();
				}
			} catch (Exception e) {
				LOG.log(Level.INFO,new StringBuilder("写文件出错 : \npath->").append(path.toString()).append(" . \nmsg->").append(e).toString());
			}
		}
		return new StringBuilder("{\"path\":\"").append(result).append("\"}").toString();
	}
	
	public boolean deleteFile(HttpServletRequest request,String name) {
		StringBuilder path = new StringBuilder(request.getSession().getServletContext().getRealPath("/"))
			.append("WEB-INF/resources/")
			.append(name);
		File mkdir = new File(path.toString());
		mkdir.delete();
		return true;
	}
	
	private void createPath(String path) {
		String p = new File(path).getParent();
		File mkdir = new File(p);
		mkdir.mkdirs();
	}
	
	private boolean uploadFile(MultipartFile file, String path){
		boolean result = false;
		return result;
	}
	
	private boolean uploadFile2(MultipartFile file, String path){
		boolean result = false;		
		InputStream stream = null;
		FileOutputStream fs = null;
		try {
			stream = file.getInputStream();
			fs = new FileOutputStream(path);
			byte[] buffer =new byte[1024*1024];
			//int bytesum = 0;
			int byteread = 0; 
			while ((byteread=stream.read(buffer))!=-1)
			{
				//bytesum += byteread;
			    fs.write(buffer,0,byteread);
			    fs.flush();
			}
			//map.put("msg", "\nFile size : "+bytesum+" bytes");
			result = true;
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		} finally{
			if (stream != null) {
				try { stream.close(); } catch (IOException e) { LOG.log(Level.WARNING,e.toString()); }
			}
			if (fs != null) {
				try { fs.close(); } catch (IOException e) { LOG.log(Level.WARNING,e.toString()); }
			}
		}
		return result;
	}
	
	private String md5Encoder(String str) throws NoSuchAlgorithmException{
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(str.getBytes());
		byte[] digesta = md5.digest();
		String result = "";
		for (byte b : digesta) {
			String stmp = Integer.toHexString(b & 0XFF);
			if (stmp.length() == 1) {
				result += "0" + stmp;
			} else {
				result += stmp;
			}
		}
		return result.toUpperCase();
	}
	
	public boolean login(long imei,String password,HttpServletRequest request){
		boolean result = false;
		try {
			password = md5Encoder(password);
			Account account = huangChengShiDao.getAccount(imei);
			if (account.getPassword().equals(password)) {
				result = true;
				setSession(request,account);
//				Account obj = (Account) request.getSession().getAttribute("recordingUser");
			}
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return result;
	}
	
	public boolean forgetPassword(long imei, String tips,String newPassword,HttpServletRequest request){
		boolean result = false;
		try {
			tips = md5Encoder(tips);
			Account account = huangChengShiDao.getAccount(imei);
			if (account.getTips().equals(tips)) {
				newPassword = md5Encoder(newPassword);
				account.setPassword(newPassword);
				setSession(request, account);
				result = true;
				huangChengShiDao.updateAccount(imei, newPassword, account.getName(), account.getSize(), account.getTime(), account.getTips(), account.getOther(), account.getEmail());
			}
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return result;
	}
	
	private void setSession(HttpServletRequest request,Account account){
		request.getSession().setAttribute("recordingUser", account);
	}
	
	private Account getAccount(HttpServletRequest request) {
		Account account = null;
		try {
			account = (Account) request.getSession().getAttribute("recordingUser");
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		return account;
	}
	
	public boolean register(	long imei,String password,String name,int size,String time,String tips,String other,String email,HttpServletRequest request) {
		boolean result = false;
		try {
			password = md5Encoder(password);
			tips = md5Encoder(tips);
			if ("".equals(time)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				time = sdf.format(new Date());
			}
			huangChengShiDao.register(imei, password, name, size, time, tips, other,email);
			result = true;
		} catch (Exception e) {
			LOG.log(Level.WARNING,e.toString());
		}
		if (result) {
			Account account = huangChengShiDao.getAccount(imei);
			setSession(request, account);
		}
		return result;
	}
}
